package com.xudow.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.multidex.MultiDexApplication;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.AuthRole;
import com.activeshare.edu.ucenter.models.base.OrderPayments;
import com.activeshare.edu.ucenter.models.course.CourseSearchCriteriaLevelOneWithOthers;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.baidu.mapapi.SDKInitializer;
import com.facebook.stetho.Stetho;
import com.jude.beam.Beam;
import com.jude.beam.expansion.list.ListConfig;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.utils.JUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.xudow.app.dynamicstate_old.ActivityDelegate;
import com.xudow.app.ui.widget.LoadingDialog;

import org.apache.http.client.CookieStore;

import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * Application
 *
 * @author lukecheng
 */
public class XApplication extends MultiDexApplication {
    private static final String TAG = makeLogTag(XApplication.class);
    private Toast toast;

    private static XApplication instance;

    public static XApplication getInstance() {
        return instance;
    }

    public void makeToast(String str) {
        if (null == toast) {
            toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT);
        }
        toast.setText(str);
        toast.show();
    }

    private CookieStore cookieStore;
    private UserProfileWithOther profile;
    private List<CourseSearchCriteriaLevelOneWithOthers> searchlist;//根据年级和兴趣 定制的筛选列表

    public List<CourseSearchCriteriaLevelOneWithOthers> getSearchlist() {
        return searchlist;
    }

    public void setSearchlist(List<CourseSearchCriteriaLevelOneWithOthers> searchlist) {
        this.searchlist = searchlist;
    }

    public UserProfileWithOther getProfile() {
        return profile;
    }

    public void setProfile(UserProfileWithOther profile) {
        this.profile = profile;
    }

    /**
     * 用户角色
     */
    private List<AuthRole> roles;

    /**
     * 用户id
     */
    private long userProfileId;
    /**
     * 融云token
     */
    private String tokenRongcloud;
    /**
     * 是否提交兴趣
     */
    private boolean hasAttentionType;
    /**
     * 需要在操作后关闭的activity
     */
    private List<Activity> chainActivities;

    /**
     * 经纬度
     */
    public Double longitude;
    public Double latitude;

    /**
     * 当前订单id
     */
    public Long currentOrderId=0l;

    /**
     * 当前payment信息
     */
    public OrderPayments currentOrderPayments;

    /**
     * 用于获取筛选level 的登录判断
     */
    public  boolean freshlogin=false;

    @Override
    public void onCreate() {
        if ("com.xudow.app".equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {

            /* IMKit SDK调用第一步 初始化 */
            RongIM.init(this);

            /* 必须在使用 RongIM 的进程注册回调、注册自定义消息等 */
            if ("com.xudow.app".equals(getCurProcessName(getApplicationContext()))) {
                PackageInfo packageInfo = null;
                try {
                    packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                } catch (PackageManager.NameNotFoundException e) {
                    LOGE(TAG, e.getMessage(), e);
                }

                //ImageLoader初始化
                initImageLoader(getApplicationContext());

                super.onCreate();
                instance = this;
                JUtils.initialize(this);
                JUtils.setDebug(BuildConfig.DEBUG, "xudow");
                JUtils.Log("launched");
                //Stetho.initializeWithDefaults(this);
                EasyRecyclerView.DEBUG = true;
                Beam.setActivityLifeCycleDelegateProvider(ActivityDelegate::new);
                ListConfig.setDefaultListConfig(new ListConfig()
                        .setLoadmoreAble(true)
                        .setRefreshAble(true)
                        .setNoMoreRes(R.layout.list_no_more));
//                registerUmengMessage();
                SDKInitializer.initialize(getApplicationContext());
            }
        }

    }

    private void registerUmengMessage() {
        PushAgent.getInstance(this).setMessageHandler(new UmengMessageHandler() {
            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                super.dealWithNotificationMessage(context, uMessage);
            }

            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
                JUtils.Log(uMessage.custom);
            }
        });
    }

    /* 一个获得当前进程的名字的方法 */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    public CookieStore getCookieStore() {
        return cookieStore;
    }

    public void setCookieStore(CookieStore cookieStore) {
        this.cookieStore = cookieStore;
    }

    /**
     * 判断是否已经登录
     */
    public boolean isLogin() {
        return null != cookieStore;
    }


    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);

        if (BuildConfig.DEBUG) {
            config.writeDebugLogs();
        }

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    /**
     * 添加Activity
     *
     * @param activity
     */
    public void addChainActivity(Activity activity) {
        if (null == chainActivities) {
            chainActivities = new ArrayList<Activity>();
        }

        chainActivities.add(activity);
    }

    /**
     * 关闭 chain activity
     */
    public void closeChainActivities() {
        if (null == chainActivities || chainActivities.size() <= 0) {
            return;
        }

        for (Activity activity : chainActivities) {
            if (null != activity) {
                try {
                    activity.finish();
                } catch (Exception e) {
                    LOGE(TAG, e.getMessage(), e);
                }
            }
        }
        chainActivities = null;
    }

    public boolean isHasAttentionType() {
        return hasAttentionType;
    }

    public void setHasAttentionType(boolean hasAttentionType) {
        this.hasAttentionType = hasAttentionType;
    }

    public String getTokenRongcloud() {
        return tokenRongcloud;
    }

    public void setTokenRongcloud(String tokenRongcloud) {
        this.tokenRongcloud = tokenRongcloud;
    }

    public List<AuthRole> getRoles() {
        return roles;
    }

    public void setRoles(List<AuthRole> roles) {
        this.roles = roles;
    }

    /**
     * 登录用户是不是学生
     *
     * @return
     */
    public boolean isStudent() {
        boolean ret = false;

        if (null != getRoles()) {
            for (AuthRole role : getRoles()) {
                //如果是学生，隐藏关联孩子信息
                if (role.getName().equals("ROLE_STUDENT")) {
                    ret = true;
                    break;
                }
            }
        }

        return ret;
    }

    public long getUserProfileId() {
        return userProfileId;
    }

    public void setUserProfileId(long userProfileId) {
        this.userProfileId = userProfileId;
    }

    public static LoadingDialog _loadingDialog;

    /**
     * 显示加载对话框
     *
     * @param message
     */
    public static void showLodingDialog(String message, Activity context) {
        if (null != _loadingDialog && _loadingDialog.isShowing()) {
            return;
        }

        _loadingDialog = new LoadingDialog(context, message);
        _loadingDialog.setCancelable(true);
        _loadingDialog.setCanceledOnTouchOutside(false);
        _loadingDialog.show();
    }

    /**
     * 隐藏登录对话框
     */
    public static void hideLoadingDialog() {
        if (null != _loadingDialog && _loadingDialog.isShowing()) {
            _loadingDialog.dismiss();
            _loadingDialog = null;
        }
    }
}
